const cloud = require('wx-server-sdk');
cloud.init();

exports.main = async (event, context) => {
  const { applicant, startDate, endDate } = event;
  const db = cloud.database();
  
  try {
    // 构建查询条件
    let query = {
      status: db.command.neq('pending'), // 排除状态为 pending 的记录
    };

    if (applicant) {
      query.applicant = db.RegExp({
        regexp: applicant,
        options: 'i', // 忽略大小写
      });
    }

    if (startDate && endDate) {
      query.applicationDate = db.command.gte(startDate).and(db.command.lte(endDate));
    } else if (startDate) {
      query.applicationDate = db.command.gte(startDate);
    } else if (endDate) {
      query.applicationDate = db.command.lte(endDate);
    }

    // 查询非 pending 状态的记录
    const recordsRes = await db.collection('records')
      .where(query)
      .orderBy('applicationDate', 'desc') // 按申请时间倒序排列
      .get();
      console.log('返回的记录:', recordsRes.data); 
    const records = recordsRes.data;

    return { success: true, data: records };
  } catch (err) {
    console.error(err);
    return { success: false, message: '查询失败，请稍后重试' };
  }
};